package service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.widget.Toast;

import com.tikeyc.mobileplayer.IMusicService;
import com.tikeyc.mobileplayer.R;
import com.tikeyc.mobileplayer.activity.AudioPlayerActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;

import domain.MediaItem;
import utils.CacheUtils;

/**
 * Created by public1 on 2017/1/11.
 */

/**startService()
 * 第一次调用：MyService()->onCreate()->onStartCommand()
 * 以后再次调用：->onStartCommand()
 * stopService()后:onDestroy()
 * */
/**bindService()
 * 第一次调用：MyService()->onCreate()->onBind()->onServiceConnected()[ServiceConnection中的回调方法]
 * onbindService():只有当前Activity与Service连接->onUnbind()->onDestroy()
 * */
public class MusicService extends Service {

    public static final String MEDIAPLAY_ONPREPARED = "com.tikeyc.mobileplayer_MediaPlayer_onPrepared";

    public static final int Music_play_Normal = 0;//顺序播放
    public static final int Music_play_Single = 1;//单曲循环
    public static final int Music_play_list_cycle = 2;//列表循环

    private MediaPlayer mediaPlayer;
    private ArrayList<MediaItem> mediaItems;
    private int position;
    private MediaItem mediaItem;

    private int music_play_model = Music_play_Normal;

    public MusicService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();

        String playModel = CacheUtils.getCacheString(this,"music_play_model");
        if (playModel != null && playModel.length() > 0) {
            music_play_model =  Integer.parseInt(playModel);
        }

        //加载音乐列表
        getDataFormLocal();
    }

    /**
     * 得到本地音乐
     */
    private void getDataFormLocal() {
        new Thread(){
            @Override
            public void run() {
                super.run();

                ContentResolver contentResolver = getContentResolver();
                Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                String[] objs = {
                        MediaStore.Audio.Media.DISPLAY_NAME,//名称
                        MediaStore.Audio.Media.DURATION,//时长
                        MediaStore.Audio.Media.SIZE,//大小
                        MediaStore.Audio.Media.DATA,//视频数据（视频绝对地址）
                        MediaStore.Audio.Media.ARTIST,//歌曲的演唱者
                };

                //
                mediaItems = new ArrayList<MediaItem>();
                Cursor cursor = contentResolver.query(uri,objs,null,null,null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {

                        MediaItem mediaItem = new MediaItem();
                        mediaItems.add(mediaItem);
                        //
                        String name = cursor.getString(0);
                        mediaItem.setName(name);

                        long duration = cursor.getLong(1);
                        mediaItem.setDuration(duration);

                        long size = cursor.getLong(2);
                        mediaItem.setSize(size);

                        String data = cursor.getString(3);
                        mediaItem.setData(data);

                        String artist = cursor.getString(4);
                        mediaItem.setArtist(artist);
                    }
                    cursor.close();
                }

            }
        }.start();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        exitMusic();
    }

    /**每次都会调用
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * @param intent
     * @return 返回对象才会去调用绑定连接的onServiceDisconnected()方法
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return stub;
//        return null;
    }



    private IMusicService.Stub stub = new IMusicService.Stub() {

        MusicService musicService = MusicService.this;

        @Override
        public void openAudio(int position) throws RemoteException {
            musicService.openAudio(position);
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void playMusic() throws RemoteException {
            musicService.playMusic();
        }

        @Override
        public void stopMusic() throws RemoteException {
            musicService.stopMusic();
        }

        @Override
        public void pauseMusic() throws RemoteException {
            musicService.pauseMusic();
        }

        @Override
        public void exitMusic() throws RemoteException {
            musicService.exitMusic();
        }

        @Override
        public int getCurrentPosition() throws RemoteException {
            return musicService.getCurrentPosition();
        }

        @Override
        public int getToalDuration() throws RemoteException {
            return musicService.getToalDuration();
        }

        @Override
        public String getArtist() throws RemoteException {
            return musicService.getArtist();
        }

        @Override
        public String getSongName() throws RemoteException {
            return musicService.getSongName();
        }

        @Override
        public String getSongPath() throws RemoteException {
            return musicService.getSongPath();
        }

        @Override
        public void palyNextMusic() throws RemoteException {
            musicService.palyNextMusic();
        }

        @Override
        public void palylastMusic() throws RemoteException {
            musicService.palylastMusic();
        }

        @Override
        public void setPalyMusicMode(int palyMusicMode) throws RemoteException {
            musicService.setPalyMusicMode(palyMusicMode);
        }

        @Override
        public int getPalyMusicMode() throws RemoteException {
            return musicService.getPalyMusicMode();
        }

        @Override
        public boolean isPlayMusic() throws RemoteException {
            return musicService.isPlayMusic();
        }

        @Override
        public void seekTo(int position) throws RemoteException {
            musicService.seekTo(position);
        }
    };




    ////////////////////////////////////   ////////////////////////////////////

    /**根据position播放对应音乐
     * @param position
     */
    private void openAudio(int position) {
        this.position = position;

        if (mediaItems != null && mediaItems.size() > 0) {

            mediaItem = mediaItems.get(position);

            if (mediaPlayer != null) {
                mediaPlayer.reset();
                mediaPlayer.release();
            }

            mediaPlayer = new MediaPlayer();
            try {
                //
                setMediaPlayerListener();
                //设置音乐播放资源
                mediaPlayer.setDataSource(mediaItem.getData());
                mediaPlayer.prepareAsync();//playMusic();


                if (music_play_model == MusicService.Music_play_Single) {
                    //单曲循环
                    mediaPlayer.setLooping(true);
                } else {
                    mediaPlayer.setLooping(false);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }else {
            Toast.makeText(this,"暂未获取到音频数据",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 设置音乐播放监听
     */
    private void setMediaPlayerListener() {
        //
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                Log.e("TAG","onPrepared MediaPlayer");
                //通知Activity获取歌曲信息
                //1.系统广播注册法
//                notifyChange(MEDIAPLAY_ONPREPARED);
                //2.EventBus注册法
                EventBus.getDefault().post(mediaItem);
                //
                playMusic();
            }
        });
        //
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                if (music_play_model != MusicService.Music_play_Single) {
                    if (music_play_model == MusicService.Music_play_Normal) {
                        if (position >= mediaItems.size() - 1){
                            return;
                        }
                    }
                    palyNextMusic();
                }
            }
        });
        //
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                return false;
            }
        });
    }

    /**发广播
     * 通知Activity获取歌曲信息
     * @param mediaplayOnprepared
     */
    private void notifyChange(String mediaplayOnprepared) {
        Intent intent = new Intent(mediaplayOnprepared);
        sendBroadcast(intent);
    }


    private NotificationManager notificationManager;
    public static String Music_Service_Notification = "Music_Service_Notification";

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void playMusic() {
        if (mediaPlayer != null) mediaPlayer.start();

        //当播放歌曲时，在状态栏显示通知栏，可操作进入播放界面
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, AudioPlayerActivity.class);
        intent.putExtra(Music_Service_Notification,true);//标识
        PendingIntent pendingIntent = PendingIntent.getActivity(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("tikeyc音乐")
                .setContentText("正在播放:" + getSongName())
                .setContentIntent(pendingIntent)
                .build();
        notificationManager.notify(1,notification);
    }

    public void stopMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();//停止
            mediaPlayer.reset();//重置
            mediaPlayer.release();//释放资源
            mediaPlayer = null;
        }
        //
        notificationManager.cancel(1);
    }

    public void pauseMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        //
        notificationManager.cancel(1);
    }

    public void exitMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();//停止
            mediaPlayer.reset();//重置
            mediaPlayer.release();//释放资源
            mediaPlayer = null;
        }
        //
        notificationManager.cancel(1);
    }

    /**得到当前播放进度
     * @return
     */
    private int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    /**得到总播放时长
     * @return
     */
    private int getToalDuration() {
        return mediaPlayer.getDuration();
    }

    /**得到当前歌手
     * @return
     */
    private String  getArtist() {
        return mediaItem.getArtist();
    }

    /**得到当前歌名
     * @return
     */
    private String getSongName() {
        return mediaItem.getName();
    }


    /**得到当前歌曲路径
     * @return
     */
    private String getSongPath() {
        return mediaItem.getData();
    }


    /**
     * 播放下一首
     */
    private void palyNextMusic(){
        //根据当前播放模式，设置下一个音频位置
        if (music_play_model == MusicService.Music_play_Normal) {
            position++;
            if (position >= mediaItems.size()){
//                stopMusic();
            }
            //
            if (position >= mediaItems.size()) {
                //已到最后一首，如果继续点击一下首 position应设置为最大值
                position =  mediaItems.size() - 1;
            }
            if (position < mediaItems.size()) {
                openAudio(position);
            }

        } else if (music_play_model == MusicService.Music_play_Single) {
            position++;
            if (position >= mediaItems.size()){
                position = 0;
            }

            //
            openAudio(position);
        } else if (music_play_model == MusicService.Music_play_list_cycle) {
            position++;
            if (position >= mediaItems.size()){
                position = 0;
            }
            //
            openAudio(position);
        }
    }

    /**
     * 播放上一首
     */
    private void palylastMusic(){
        //根据当前播放模式，设置上一个音频位置
        if (music_play_model == MusicService.Music_play_Normal) {
            position--;
            if (position < 0){
                //已到第一首，如果继续点上一首 position应设置为最小值
                position =  0;
//                stopMusic();
            }
            //
            if (position >= 0 && position < mediaItems.size()) {
                openAudio(position);
            }
        } else if (music_play_model == MusicService.Music_play_Single) {
            position--;
            if (position < 0){
                position = 0;
            }

            //
            openAudio(position);
        } else if (music_play_model == MusicService.Music_play_list_cycle) {
            position--;
            if (position < 0){
                position = mediaItems.size() - 1;
            }
            //
            openAudio(position);
        }
    }

    /**
     * 设置播放模式，单曲混合等
     */
    private void setPalyMusicMode(int palyMusicMode){
        this.music_play_model = palyMusicMode;
        //
        CacheUtils.cacheString(this,"music_play_model",""+music_play_model);

        //
        if (music_play_model == MusicService.Music_play_Single) {
            //单曲循环
            mediaPlayer.setLooping(true);
        } else {
            mediaPlayer.setLooping(false);
        }
    }

    /**
     *得到播放模式
     */
    private int getPalyMusicMode(){

        return music_play_model;
    }

    /**是否正在播放
     * @return
     */
    private boolean isPlayMusic(){
        return mediaPlayer.isPlaying();
    }


    /**拖拽音频
     * @param position
     */
    private void seekTo(int position){
        mediaPlayer.seekTo(position);
    }
}
